//
// Created by ych on 2/13/24.
//
#include "ych_state.h"

void initYState(YState *y_state,int mode) {
    initErrorStack(&y_state->errors);
    y_state->mode=mode;
}
void startYState(YState *y_state){
    initReader1(&y_state->reader,y_state);
    initErrorStack(&y_state->errors);
    initLexer(&y_state->lexer, y_state);
    memset(&y_state->memory, 0, sizeof(VMMemory));
    initParser(&y_state->parser, y_state);
    initExecutor(&y_state->executor, y_state,y_state->memory.VM_I, &y_state->memory);
}
void run1YState(YState *y_state,char *buffer){
    readLine(&y_state->reader, buffer);
    y_state->parser.current_token = getNextToken(&y_state->lexer);
    recordSemantics(&y_state->parser);
    while (analyzeStatementParser(&y_state->parser) != PARSER_END){
        if(y_state->mode==YSTATE_INTERACTIVE){
            recordSemantics(&y_state->parser);
            clearStage(&y_state->parser);
        }
    }
    clearStage(&y_state->parser);
    runExecutor(&y_state->executor);
}
void run2YState(YState *y_state, char *file_path) {
    initErrorStack(&y_state->errors);
    initReader2(&y_state->reader, y_state, file_path);
    readFile(&y_state->reader);
    initLexer(&y_state->lexer, y_state);
    memset(&y_state->memory, 0, sizeof(VMMemory));
    initParser(&y_state->parser, y_state);
    initExecutor(&y_state->executor, y_state,y_state->memory.VM_I, &y_state->memory);
    analyzeParser(&y_state->parser);
    runExecutor(&y_state->executor);
}
void rollbackYState(YState *y_state){
    rollbackReader(&y_state->reader);
    rollbackSemantics(&y_state->parser);
}
void showErrors(YState *y_state){
    while (!isEmptyErrorStack(&y_state->errors)) {
        Error e = popErrorStack(&y_state->errors);
        printf("%s\n", e.info.data);
        freeYString(&e.info);
    }
    printf("ERROR\n");
}
void freeMemory(YState *y_state){
    for(int i=y_state->parser.c_state.vm_string_const_p-1;i>=0;--i){
        freeYString(y_state->memory.VM_STR_CONST);
    }
}
void destroyYState(YState *y_state) {
    freeMemory(y_state);
    freeExecutor(&y_state->executor);
    freeParser(&y_state->parser);
    freeLexer(&y_state->lexer);
    freeReader(&y_state->reader);
    freeErrorStack(&y_state->errors);
}